package com.pap.rbac.resource.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.stuxuhai.jpinyin.PinyinFormat;
import com.github.stuxuhai.jpinyin.PinyinHelper;
import com.pap.base.controller.BaseController;
import com.pap.base.util.date.DateUtils;
import com.pap.base.util.jackson.JacksonUtilss;
import com.pap.base.util.string.StringUtilss;
import com.pap.obj.vo.business.StatusFlagEnum;
import com.pap.obj.vo.response.ResponseVO;
import com.pap.rbac.agent.resource.IResourceAgent;
import com.pap.rbac.agent.resource.dto.ResourceTreeNodeVO;
import com.pap.rbac.resource.auto.entity.Resource;

@RestController
@RequestMapping("/v1/rbac/resource")
public class ResourceController extends BaseController<Resource, IResourceAgent> {

	private static Logger logger  =  LoggerFactory.getLogger(ResourceController.class);
	
	@javax.annotation.Resource(name = "resourceAgent")
	@Override
	public void setService(IResourceAgent agent) {
		super.service = agent;
	}
	
	@RequestMapping(value = "/treejson", method = {RequestMethod.GET})
	public List<ResourceTreeNodeVO> treeJSON(@RequestHeader(value = "clientLicenseId", defaultValue = "-1") String clientLicenseId,
			@RequestHeader(value = "loginUserId", defaultValue = "-1") String loginUserId) {
		//  全局默认角色的顶层编码为 -1 
		String globalParentId = "-1";
		return service.resourceTreeJson(clientLicenseId, globalParentId);
	}
	
	/**
	 * 角色保存
	 * 必须输入参数为角色名称
	 */
	@Override
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/add", method = {RequestMethod.POST})
	public ResponseVO<Resource> add(@RequestHeader(value = "clientLicenseId", defaultValue = "-1") String clientLicenseId,
			@RequestHeader(value = "loginUserId", defaultValue = "-1") String loginUserId,
			@RequestParam(value = "addJSON", required = true) String addJSON) throws Exception {
		
		ObjectMapper objectMapper = JacksonUtilss.getObjectMapper();
		Resource resource = objectMapper.readValue(addJSON, Resource.class);
		resource.setId(UUID.randomUUID().toString());
		
		
		if(resource != null && 
				StringUtilss.isNotEmpty(resource.getName())) {
			// 如果前端没有传递过来code值，则默认使用拼音代替
			if(StringUtilss.isEmpty(resource.getCode())) {
				resource.setCode(PinyinHelper.convertToPinyinString(resource.getName(), "", PinyinFormat.WITHOUT_TONE));
			}
			resource.setLevel("0");
			// 处理父级数据
			Resource parentResource = service.selectByPrimaryKey(resource.getParentId());
			if(parentResource != null) {
				// pathId
				if(StringUtilss.isNotEmpty(parentResource.getPathIds())) {
					resource.setPathIds(parentResource.getPathIds() + "," + parentResource.getId());
				} else {
					resource.setPathIds(parentResource.getId());
				}
				// pathCode
				if(StringUtilss.isNotEmpty(parentResource.getPathCodes())) {
					resource.setPathCodes(parentResource.getPathCodes() + "," + parentResource.getCode());
				} else {
					resource.setPathCodes(parentResource.getCode());
				}
				// pathName
				if(StringUtilss.isNotEmpty(parentResource.getPathNames())) {
					resource.setPathNames(parentResource.getPathNames() + "," + parentResource.getName());
				} else {
					resource.setPathNames(parentResource.getName());
				}
				// level
				if(StringUtilss.isNotEmpty(parentResource.getLevel())) {
					resource.setLevel((Integer.parseInt(parentResource.getLevel()) + 1) + "");
				} else {
					resource.setLevel("0");
				}
			} 
			resource.setStatus(StatusFlagEnum.YES.getKey());
			resource.setCreateIp("0.0.0.0");
			resource.setCreateTime(DateUtils.getCurrDateTimeStr());
			resource.setCreateUser(loginUserId);
			resource.setClientLicenseId(clientLicenseId);
			resource.setParentId(StringUtilss.isNotEmpty(resource.getParentId()) == true ? resource.getParentId() : "-1");
			
			int operationInt = service.insertSelective(resource);
			
			return ResponseVO.successdata(operationInt);
			
		} else {
			return ResponseVO.validfail("入参异常，请判断是否含有角色名称");
		}

	}
	
	@Override
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/delete")
	public ResponseVO<Resource> delete(@RequestHeader(value = "clientLicenseId", defaultValue = "-1") String clientLicenseId,
			@RequestHeader(value = "loginUserId", defaultValue = "-1") String loginUserId,
			@RequestParam(value = "deleteJSON", required = true) String deleteJSON) throws Exception {

		ObjectMapper objectMapper = JacksonUtilss.getObjectMapper();
		Resource resource = objectMapper.readValue(deleteJSON, Resource.class);
		if(resource != null && StringUtilss.isNotEmpty(resource.getId())) {
			Map<Object, Object> pathIdsMap = new HashMap<Object, Object>();
			pathIdsMap.put("myLike_pathIds", resource.getId());
			List<Resource> ResourceList = service.selectListByMap(pathIdsMap);
			if(ResourceList != null && ResourceList.size() > 0) {
				return ResponseVO.validfail("请检查入参，此角色被其他資源所依赖!");
			} else {
				int operationInt = service.deleteByPrimaryKey(resource.getId());
				return ResponseVO.successdata(operationInt);
			}
		} else { 
			return ResponseVO.validfail("入参异常，请判断是否含有資源编码");
		}
	}
	
	@Override
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/update", method = {RequestMethod.POST})
	public ResponseVO<Resource> update(@RequestHeader(value = "clientLicenseId", defaultValue = "-1") String clientLicenseId,
			@RequestHeader(value = "loginUserId", defaultValue = "-1") String loginUserId,
			@RequestParam(value = "updateJSON", required = true) String updateJSON) 
					throws IOException, JsonParseException, JsonMappingException {
		
		ObjectMapper objectMapper = JacksonUtilss.getObjectMapper();
		Resource resource = objectMapper.readValue(updateJSON, Resource.class);
		
		ResponseVO<Resource> responseVO = service.updateAndCheckResource(resource, loginUserId);
		return responseVO;
	}
	
	/**
	 * 查询所有此系统下的资源菜单，扁平型的结构
	 * @param clientLicenseId
	 * @param loginUserId
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/resourceflat", method = {RequestMethod.GET})
	public ResponseVO<Resource> resourceFlat(@RequestHeader(value = "clientLicenseId", defaultValue = "-1") String clientLicenseId,
			@RequestHeader(value = "loginUserId", defaultValue = "-1") String loginUserId,
			@RequestParam String userId) throws Exception {
		HashSet<Resource> allResourceList = new HashSet<Resource>();
		
		List<Resource> operationList = service.selectListByUserAndLicense(userId, clientLicenseId);
		if(operationList != null && operationList.size() > 0) {
			for (Resource resource : operationList) {
				String parentIds = resource.getPathIds();
				if(StringUtilss.isNotEmpty(parentIds)) {
					String[] parentArray = parentIds.split(",");
					for (int i = 0; i < parentArray.length; i++) {
						Resource temp = service.selectByPrimaryKey(parentArray[i]);
						if(temp != null) {
							allResourceList.add(temp);
						}
					}
				}
				allResourceList.add(resource);
			}
		}
		
		return ResponseVO.successdatas(allResourceList, null);
	}
}
